<template>
  <div class="bills">
    <div class="head-con">
      <div class="searchDiv">
        <label class="label_input">
          <span style="color: red">*</span>供应商:</label
        >
        <el-input
          v-model="form.supplier_name"
          style="width: 220px"
          placeholder="选择供应商(必选)"
          clearable
        >
          <template #append>
            <el-button :icon="Search" @click="supplierDialog.open()" />
          </template>
        </el-input>

        <!-- 源单对话框 -->
        <SourceDocDialog
          ref="sourceDocDialog"
          :source-doc-list="availableSourceDocs"
          @confirm="handleSourceDocConfirm"
        />

        <!-- 供应商对话框 -->
        <SupplierDialog ref="supplierDialog" @confirm="handleSupplierConfirm" />
      </div>

      <div class="searchDiv">
        <label class="label_input">总欠款:</label>
        <el-input
          v-model="TotalDebt"
          style="width: 100px"
          disabled
          placeholder="0.00"
        />
      </div>

      <div class="searchDiv">
        <label class="label_input">负责人:</label>
        <el-select
          v-model="responsible"
          style="width: 130px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in responsibleOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="searchDiv">
        <label class="label_input">单据日期:</label>
        <el-date-picker v-model="date" type="date" />
      </div>
      <div class="searchDiv">
        <label class="label_input">单据编号:</label>
        <span v-if="!editingBillNo" @click="editBillNo" class="bill-no">{{
          billNo
        }}</span>
        <el-input
          v-else
          v-model="tempBillNo"
          ref="billNoInput"
          style="width: 150px"
          @blur="saveBillNo"
          @keyup.enter="saveBillNo"
        />
      </div>
      <hr />
    </div>

    <div class="settlement-table">
      <el-table
        :data="settlementItems"
        style="width: 100%"
        border
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :cell-style="tableCellStyle"
      >
        <el-table-column type="index" label="序号" width="50" align="center">
          <template #default="{ $index, row }">
            <span v-if="!row.isTotalRow">{{ $index + 1 }}</span>
            <span v-else></span>
          </template>
        </el-table-column>

        <el-table-column prop="account" label="*结算账户" min-width="150">
          <template #default="{ row }">
            <el-select
              v-model="row.account"
              placeholder="请先选择结算账户"
              style="width: 100%"
              v-if="!row.isTotalRow"
              :disabled="!handleSourceDocConfirm"  
            >
              <el-option
                v-for="item in accountList"
                :key="item.value"  
                :label="item.label"  
                :value="item.value"  
              />
            </el-select>
            <span v-else> 合计: </span>
          </template>
        </el-table-column>

        <el-table-column prop="amount" label="*付款金额" min-width="120">
          <template #default="{ row }">
            <el-input
              v-model.number="row.amount"
              type="number"
              placeholder="0.00"
              step="0.01"
              style="width: 100%"
              @change="calculateTotal"
              v-if="!row.isTotalRow"
            />
            <span v-else>{{ totalAmount }} </span>
          </template>
        </el-table-column>

        <el-table-column prop="method" label="结算方式" min-width="120">
          <template #default="{ row }">
            <el-select
              v-model="row.method"
              placeholder="请选择结算方式"
              style="width: 100%"
              v-if="!row.isTotalRow"
            >
              <el-option label="银行转账" value="transfer" />
              <el-option label="支票" value="check" />
              <el-option label="汇票" value="draft" />
              <el-option label="现金" value="cash" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="settlementNo" label="结算号" min-width="130">
          <template #default="{ row }">
            <el-input
              v-model="row.settlementNo"
              placeholder="结算号"
              style="width: 100%"
              v-if="!row.isTotalRow"
            />
          </template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" min-width="150">
          <template #default="{ row }">
            <el-input
              v-model="row.remark"
              placeholder="备注信息"
              style="width: 100%"
              v-if="!row.isTotalRow"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="80" align="center">
          <template #default="{ $index }">
            <el-button
              type="text"
              size="small"
              :icon="CirclePlus"
              @click="addSettlementRow($index)"
              v-if="isTotalRow($index)"
            />
            <el-button
              type="text"
              size="small"
              :icon="Delete"
              @click="removeSettlementRow($index)"
              v-if="isDeleteRow($index)"
              style="color: #f56c6c"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="middle-div">
      <el-button round :disabled="!handleSupplierConfirm" @click="sourceDocDialog.open()">选择源单</el-button>
      <el-button round @click="autoWriteOff">自动核销</el-button>
    </div>

    <div class="settlement-table">
      <el-table
        :data="SourceDocuments.length>0?SourceDocuments:placeholderRows"
        style="width: 100%"
        border
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :cell-style="tableCellStyle"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="docNo" label="源单编号" min-width="120">
          <template #default="{ row }">
            <span v-if="row.docNo" class="link-text">{{ row.docNo }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="businessType" label="业务类别" min-width="100" />
        <el-table-column prop="docDate" label="单据日期" min-width="110" />
        <el-table-column label="单据金额" min-width="100">
          <template #default="{ row }">
            <span v-if="row.docNo">
              {{ Number(row.slipPrice).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="writtenOffAmount"
          label="已核销金额"
          min-width="110"
        >
        <template #default="{ row }">
          <span v-if="row.docNo">
            {{ Number(row.writtenOffAmount).toFixed(2) }}
          </span>
        </template>
        </el-table-column>
        <el-table-column
          prop="unwrittenOffAmount"
          label="未核销金额"
          min-width="110"
        />
        <el-table-column
          prop="currentWriteOffAmount"
          label="*本次核销金额"
          min-width="130"
        >
          <template #default="{ row }">
            <el-input
              v-model.number="row.currentWriteOffAmount"
              type="number"
              step="0.01"
              style="width: 100px"
              :min="row.isRefund === 0 ? 0.01 : -Infinity" 
              :max="row.isRefund === 0 ? row.unwrittenOffAmount : 0"
              @keydown="preventInvalidInput($event, row)" 
              @change="validateWriteOffAmount(row)"
              @blur="validateWriteOffAmount(row)"
              @input="handleWriteOffInput(row)"
              v-if="row.docNo"
            />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="单据备注" min-width="150" />
        <el-table-column label="操作" width="80" align="center">
          <template #default="{ $index }">
            <el-button
              type="text"
              size="small"
              :icon="CirclePlus"
              @click="addSourceDocRow"
              v-if="isSourceDocLastRow($index)"
            />
            <el-button
              type="text"
              size="small"
              :icon="Delete"
              @click="removeSourceDocRow($index)"
              v-if="canDeleteSourceDocRow($index)"
              style="color: #f56c6c"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="note">
      <el-input v-model="note" :rows="2" type="textarea" placeholder="备注" />
    </div>

    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;
      "
    >
      <div>
        <span>本次预付款:</span>
        <el-input-number
          v-model="remainAmount"
          :precision="2"
          :min="0"
          :controls="false"
          :disabled="true"
          style="margin-left: 10px; width: 150px"
        ></el-input-number>
      </div>

      <div style="position: fixed; top: 150px; right: 50px; z-index: 9999; display: flex; gap: 1px;">
        <el-button type="primary" @click="addNew" style="font-size:12px">新增</el-button>
        <el-button type="primary" @click="save" style="font-size:12px">保存</el-button>
        <el-button type="primary" @click="putit" style="font-size:12px">提交</el-button>
        <el-button type="primary" @click="handleAudit" style="font-size:12px">审核</el-button>
        <el-button type="primary" @click="back" style="font-size:12px">驳回</el-button>
      </div>

      <div class="status-indicator" v-if="showStatus">
        <img :src="statusImageUrl" :alt="statusAltText" class="status-image" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from "vue";
import { Search, CirclePlus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import SourceDocDialog from "@/util/SourceDocDialog.vue";
import SupplierDialog from "@/util/SupplierDialog.vue";
import dayjs from "dayjs";
import axios from "axios";
import { useRoute,useRouter } from 'vue-router';
const router = useRouter();
const route = useRoute();


//显示欠款
const TotalDebt = ref("");
//负责人选择
const responsible = ref("");
//单据选择
const date = ref(dayjs().format('YYYY-MM-DD'))

//空数据
const placeholderRows = ref(Array(5).fill({ isPlaceholder: true })); // 5行空数据

//业务员数据绑定

// 对话框引用
const supplierDialog = ref(null);
const sourceDocDialog = ref(null);
// const Supplier = ref("");
//表单数据
const form = reactive({
  supplier_name: "",
  supplier_code: ""
});
// 选中的供应商
const selectedSupplier = ref({
  SupplierId:"",
  SupplierName: "",
  SupplierCode: ""
});
// const selectedSupplier = ref({
// });
// 处理供应商选择确认
const handleSupplierConfirm = (supplier) => {
  console.log('接收到的完整供应商数据:', supplier);
  console.log('供应商ID:', supplier.rawData.id, '类型:', typeof supplier.id);
  
  // 确保正确设置 selectedSupplier
  selectedSupplier.value = {
    id: supplier.id,
    SupplierId:supplier.rawData?.id,
    SupplierName: supplier.SupplierName,
    SupplierCode: supplier.SupplierCode,
    
  };
  ElMessage.success(`已选择供应商：${supplier.SupplierName}`);
  TotalDebt.value = (supplier.rawData.initialPayable - supplier.rawData.initialAdvance).toFixed(2);
  form.supplier_name = supplier.SupplierName;
  form.supplier_code = supplier.SupplierCode;
  selectedSupplier.value=supplier
  getAvailableSourceDocs();
};
console.log('选中的供应商',selectedSupplier.value)

// 处理源单选择确认
const handleSourceDocConfirm = (docs) => {
  const newDocs = docs.map((doc) => ({
    ...doc,
    currentWriteOffAmount: 0,
  }));
  if (isEditMode.value && SourceDocuments.value.length > 0) {
    const existingDocNos = new Set(SourceDocuments.value.map(d => d.docNo));
    const uniqueNewDocs = newDocs.filter(doc => !existingDocNos.has(doc.docNo));

    SourceDocuments.value = [...SourceDocuments.value, ...uniqueNewDocs];
  } else {
    // 首次选择或新增模式：直接覆盖
    SourceDocuments.value = newDocs;
  }
  calculateTotal();
};

onMounted(async () => {
  await Promise.all([
    getSupplierList(),
    getAccountList(),
  ]);

  // 再处理单据逻辑
  if (isEditMode.value) {
    await loadPaymentData(route.query.code);
  } else {
    generateDefaultBillNo();
  }
});

// 结算账户列表
const accountList = ref([]);
// 页面加载时获取结算账户列表
const getAccountList = async () => {
  try {
    const response = await axios.get("/finance/allAccount",{params:{company_code:'GS0001'}});
    if (response.data.code === 5200) {
      accountList.value = response.data.allAccount.map(account => ({
        label: account.account_name, 
        value: account.account_code 
      }));
    } else {
      ElMessage.error("获取结算账户失败：" + response.data.msg);
    }
  } catch (error) {
    console.error("获取结算账户出错：", error);
    ElMessage.error("网络错误，无法获取结算账户数据");
  }
};
//供应商列表
const supplierList = ref([]);
const getSupplierList = async () => {
  try {
    const response = await axios.get("/finance/getSupplierList",{params:{pageNum:1,pageSize:100}});
    if (response.data.code === 5200) {
      supplierList.value = response.data.supplierList.pageInfo.list;
      console.log('supplierList1',supplierList.value)
    } else {
      ElMessage.error("获取供应商失败：" + response.data.msg);
    }
  } catch (error) {
    console.error("获取供应商出错：", error);
    ElMessage.error("网络错误，无法获取供应商数据");
  }
};
// 单据编号相关
const billNo = ref("");
const tempBillNo = ref("");
const editingBillNo = ref(false);
const billNoInput = ref(null);

    
// 编辑模式**********
const payment_id = ref([]);
const isEditMode = computed(() => !!route.query.code);
console.log('isedit',isEditMode.value)
const loadPaymentData = async (paymentCode) => {
  console.log('code',paymentCode)
  try {
    const response = await axios.get('/finance/getPaymentByCode', {
      params: { payment_code:paymentCode }
    });

    const data = response.data.payment;
    console.log('data',data)
    // 基础信息
    payment_id.value= data.payment_id;
    billNo.value = data.payment_code;
    tempBillNo.value = data.payment_code;
    date.value = data.payment_date;
    note.value = data.memo || '';
    const selectedSupplierForEdit = supplierList.value.find(c => String(c.id) === String(data.supplier_id)) || null;
    selectedSupplier.value = {
      id: selectedSupplierForEdit.id, 
      SupplierName: selectedSupplierForEdit.name,
      SupplierCode: selectedSupplierForEdit.code,
      rawData: selectedSupplierForEdit
    };
    // 供应商信息
    handleSupplierConfirm.value = supplierList.value.find(c => String(c.id) === String(data.supplier_id)) || null;
    console.log('handleSupplier',handleSupplierConfirm.value)
    form.supplier_name = handleSupplierConfirm.value?.name || '';
    TotalDebt.value = (
      (handleSupplierConfirm.value?.initialPayable || 0) - 
      (handleSupplierConfirm.value?.initialAdvance || 0)
    ).toFixed(2);
    getAvailableSourceDocs();
    // 结算账户明细
    settlementItems.value = [];
    if (data.paymentAccountList && data.paymentAccountList.length > 0) {
      for (const acc of data.paymentAccountList) {
        settlementItems.value.push({
          account: acc.account_code,
          amount: Number(acc.amount) || 0,
          settlementNo: acc.settlement_no || '',
          // remark: acc.remark || ''
        });
      }
    } else {
      // 兜底：至少一行
      settlementItems.value.push({
        account: data.account_id || '',
        amount: Number(data.amount) || 0,
        settlementNo: '',
        // remark: ''
      });
    }
    console.log('settle',settlementItems)

    // 添加合计行
    settlementItems.value.push({
      account: "合计:",
      amount: totalAmount.value,
      method: "",
      settlementNo: "",
      remark: "",
      isTotalRow: true,
    });

    calculateTotal(); // 触发合计计算

    // 源单明细（SourceDocuments）
    SourceDocuments.value = [];
    if (data.procurementList && data.procurementList.length > 0) {
      console.log('whfksjdf',data.procurementList)
      SourceDocuments.value = data.procurementList.map(doc => {
        const isRefund = doc.isRefund === 1;
        const slipPrice = isRefund ? -Number(doc.procurement_amount) : Number(doc.procurement_amount);
        const writtenOffAmount = isRefund ? -Number(doc.written_off_amount) : Number(doc.written_off_amount);
        const currentWriteOffAmount = isRefund ? -Number(doc.current_written_off_amount) : Number(doc.current_written_off_amount);

        return {
          docId: doc.procurement_id,
          docNo: doc.procurement_code,
          businessType: isRefund ? '采购退货' : '普通采购',
          docDate: doc.procurement_date,
          docAmount: slipPrice,
          slipPrice: slipPrice,
          pay_amount: doc.pay_amount || 0,
          writtenOffAmount: writtenOffAmount, // ← 负数！
          currentWriteOffAmount: currentWriteOffAmount, // ← 负数！
          get unwrittenOffAmount() {
            return (this.slipPrice - this.writtenOffAmount);
          },
          remark: doc.remarks || ''
        };
      });
    }

    // 状态图片（如果已审核）
    if (data.status === 2) {
      showStatus.value = true;
      statusImageUrl.value = imagePaths.passed;
      statusAltText.value = "审核通过";
    }

  } catch (error) {
    console.error('加载收款单失败:', error);
    ElMessage.error('加载收款单失败，请重试');
  } 
};

// *************




// 生成默认单据编号 
const generateDefaultBillNo = async () => {
  try {
    // 从后端获取最新序号
    const response = await axios.get("/finance/getNextPaymentNo");
    console.log('最新序号',response.data)
    if (response.data.code === 5200) {
      billNo.value = response.data.billNo;
      tempBillNo.value = billNo.value;
    } else {
      // 后端获取失败时使用本地默认值
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      billNo.value = `RECEIPT${year}${month}${day}001`;
      tempBillNo.value = billNo.value;
    }
  } catch (error) {
    console.error("获取单据编号失败：", error);
    // 网络错误时使用本地默认值
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    billNo.value = `RECEIPT${year}${month}${day}001`;
    tempBillNo.value = billNo.value;
  }
};

//源单数据
const SourceDocuments = ref([]);
// 模拟可选的源单数据（本地数据）
const availableSourceDocs = ref([]);
// 获取可用的源单数据（销售单据）
const getAvailableSourceDocs = async () => {
  if (!selectedSupplier.value) {
    ElMessage.warning("请先选择供应商");
    return;
  }

  console.log('已选择供应商:', selectedSupplier.value)
  try {
    const response = await axios.get('/finance/getProcumentList', {
      params: { pageNum:1,pageSize:10,companyCode:'GS0001',supplier_code: selectedSupplier.value.SupplierCode }
    });
    // console.log('接受的采购单数据', response.data)
    if (response.data.code === '5200') {
      const paymentData = response.data.procurementPageInfo.list;

      // let formattedDocs = [];
      // if (Array.isArray(paymentData)) {
      //   formattedDocs = paymentData;
      // } else if (paymentData && typeof paymentData === 'object') {
      //   formattedDocs = [paymentData];
      // } else {
      //   formattedDocs = [];
      // }
      console.log('接受的采购单数据',paymentData)
      // 确保使用最新的已核销金额数据
      availableSourceDocs.value = paymentData.map(doc => {
        const slipPrice = doc.isRefund===1 ? -Number(doc.procurement_amount) : Number(doc.procurement_amount);
        const writtenOffAmount = doc.isRefund===1 ? -Number(doc.written_off_amount || 0) : Number(doc.written_off_amount || 0);

        return {
          docId: doc.procurement_id,
          docNo: doc.procurement_code,
          businessType: doc.isRefund===1 ? '采购退货' : '普通采购',
          isRefund: doc.isRefund,
          docDate: doc.created_date,
          procurement_amount: Number(doc.procurement_amount) || 0,
          slipPrice: slipPrice,
          pay_amount: Number(doc.pay_amount) || 0,
          writtenOffAmount: writtenOffAmount, 
          get unwrittenOffAmount() {
            return (this.slipPrice - this.writtenOffAmount);
          },
          remark: doc.remarks || "",
          customer_code: doc.customer_code
        };
      });
      
      console.log('格式化后的源单数据:', availableSourceDocs.value);
      ElMessage.success("获取源单数据成功");
    } else {
      ElMessage.error("获取源单数据失败：" + response.data.msg);
      availableSourceDocs.value = [];
    }
  } catch (error) {
    console.error("获取源单数据出错：", error);
    ElMessage.error("网络错误，无法获取源单数据");
    availableSourceDocs.value = [];
  }
};

let responsibleOptions = ref([
  {
    id: "1",
    label: "老板",
  },
  {
    id: "2",
    label: "组长-老陈",
  },
  {
    id: "3",
    label: "采购组员-小鹏",
  },
  {
    id: "4",
    label: "采购组员-小亮",
  },
]);


const validateAllWriteOffAmounts = () => {
  for (const doc of SourceDocuments.value) {
    if (!doc.docNo) continue;

    const current = Number(doc.currentWriteOffAmount) || 0;

    // 普通采购校验
    if (doc.isRefund === 0) {
      if (current <= 0) {
        ElMessage.warning(`源单 ${doc.docNo} 为普通采购，核销金额必须大于0`);
        return false;
      }
      const unwritten = Number(doc.unwrittenOffAmount) || 0;
      if (current > unwritten) {
        ElMessage.warning(`源单 ${doc.docNo} 核销金额不能超过${unwritten.toFixed(2)}`);
        return false;
      }
    }

    // 采购退货校验
    if (doc.isRefund === 1) {
      if (current >= 0) {
        ElMessage.warning(`源单 ${doc.docNo} 为采购退货，核销金额必须为负数`);
        return false;
      }
      const unwrittenAbs = Math.abs(Number(doc.unwrittenOffAmount) || 0);
      if (Math.abs(current) > unwrittenAbs) {
        ElMessage.warning(`源单 ${doc.docNo} 核销金额的绝对值不能超过${unwrittenAbs.toFixed(2)}`);
        return false;
      }
    }
  }
  return true;
};

const payment = ref(null);
//保存
const save = () => {
    console.log('selectedSupplier.value:', selectedSupplier.value);
  console.log('供应商ID:', selectedSupplier.value.rawData?.id);
  console.log('表单数据:', form);
  // 1. 验证是否选择供应商
  if (!selectedSupplier.value) {
    ElMessage.warning("请先选择供应商");
    return;
  }

  if (!validateAllWriteOffAmounts()) {
    return;
  }

  // 2. 验证所有结算行
  for (const item of settlementItems.value) {
    if (item.isTotalRow) continue;
    
    // 验证结算账户
    if (!item.account) {
      ElMessage.warning("请选择结算账户");
      return;
    }
    
    // 验证付款金额
    if (!item.amount || item.amount <= 0.01) {
      ElMessage.warning("付款金额必须大于0.01");
      return;
    }
  }
  // for (const doc of SourceDocuments.value) {
  //   if (doc.isRefund === 1 && doc.currentWriteOffAmount >= 0) {
  //     ElMessage.warning(`源单 ${doc.docNo} 为采购退货，本次核销金额必须为负数`);
  //     return;
  //   }
  // }

  // 3. 构造付款单数据
  const paymentData = {
    ...(isEditMode.value && { payment_id: payment_id.value }),
    payment_code: billNo.value,
    supplier_id: selectedSupplier.value.rawData.id,
    supplier_code: selectedSupplier.value.SupplierCode,
    amount: totalAmount.value,
    payment_method: settlementItems.value[0]?.method || '', 
    payment_date: date.value,
    status: 0, // 已保存未审核
    account_id: settlementItems.value[0]?.account || '', // 结算账户ID
    company_code: 'GS0001', 
    // 传递多个结算账户
    accountList: settlementItems.value
      .filter(item => !item.isTotalRow && item.account) // 过滤掉合计行和空账户
      .map(item => ({
        account_code: item.account, // 账户编码
        account_name: accountList.value.find(acc => acc.value === item.account)?.label || '', // 账户名称
        amount: item.amount || 0 // 该账户的付款金额
      })),
    current_written_off_all_amount: totalWriteOff.value,
    written_off_amount: 0.00,
    procurementList: SourceDocuments.value
      .filter(doc => doc.docNo)
      .map(doc => ({
        procurement_id:doc.docId,
        procurement_code: doc.docNo, // 销售单据编号
        procurement_date: doc.docDate, // 单据日期
        isRefund:doc.type,
        remarks: doc.remark || '', // 备注
        supplier_code: selectedSupplier.value?.supplier_code || '', // 供应商编号
        company_code: 'GS0001', // 公司编码
        slipPrice: doc.docAmount,
        current_written_off_amount: doc.currentWriteOffAmount || 0, // 本次核销金额
        written_off_amount: doc.writtenOffAmount || 0 , // 已核销金额
      }))
      
  };

  console.log('保存的付款单数据:', isEditMode.value,paymentData);
  const url=isEditMode.value?'/finance/updatePaymentOrder':'/finance/addPayment';
  axios.post(url,paymentData)
    .then(response => {
      console.log('sfwefwfsdfsf',response.data)
      if (response.data.code === 5200) {
        ElMessage.success(isEditMode.value?"付款单修改成功":"付款单保存成功");
      }else if(response.data.code===5500){
        console.log(isEditMode.value?"修改失败：":"保存失败：",response.data.msg);
        ElMessage.error(isEditMode.value?"修改失败":"保存失败");
      }
    })
    .catch(error => {
      console.error(isEditMode.value?"修改付款单出错：":"保存付款单出错：", error);
      ElMessage.error("网络错误，付款单保存失败");
    });
};

//提交
const putit = async () => {
  try{
    const response = await axios.get('/finance/getPaymentByCode',{params:{payment_code:billNo.value}});
    payment.value = response.data.payment;
    console.log('得到的付款单',payment.value)
    if(response.data.code===5500){
      ElMessage.error('该单据未保存，无法提交');
      return;
    }
    if(payment.value.status===1 || payment.value.status===2){
      ElMessage.error('该单据已提交或已审核，无法提交!!!');
      return;
    }
    const res = await axios.get('/finance/updatePaymentStatus', {
      params: {status: 1,payment_code: billNo.value}
    });
    if(res.data.code===5200){
      ElMessage.success('提交成功');
    }else{
      console.log('提交失败',res.data)
      ElMessage.error('提交失败');
    }
  }catch(error){
    console.log('提交失败',error);
    ElMessage.error('网络错误，失败')
  }
};

//审核
const handleAudit = async () => {
  try{
    const response = await axios.get('/finance/getPaymentByCode',{params:{payment_code:billNo.value}});
    payment.value = response.data.payment;
    console.log('得到的付款单',payment.value)
    if(response.data.code===5500){
      ElMessage.error('该单据未提交，无法审核');
      return;
    }
    if(payment.value.status!==1){
      ElMessage.error('该单据未提交或已审核，无法审核!!!');
      return;
    }
    const res = await axios.get('/finance/updatePaymentStatus', {
      params: {status: 2,payment_code: billNo.value}
    });
    if(res.data.code===5200){
      ElMessage.success('审核成功');
    }else{
      console.log('审核失败',res.data)
      ElMessage.error('审核失败');
    }
  }catch(error){
    console.log('审核失败',error);
    ElMessage.error('网络错误，失败')
  }
};
//驳回
const back = async () => {
  try{
    const response = await axios.get('/finance/getPaymentByCode',{params:{payment_code:billNo.value}});
    payment.value = response.data.payment;
    console.log('得到的付款单',payment.value)
    if(response.data.code===5500){
      ElMessage.error('该单据未提交，无法驳回');
      return;
    }
    if(payment.value.status!==1){
      ElMessage.error('该单据不是已提交状态，无法驳回!!!');
      return;
    }
    const res = await axios.get('/finance/updatePaymentStatus', {
      params: {status: 3,payment_code: billNo.value}
    });
    if(res.data.code===5200){
      ElMessage.success('驳回成功');
    }else{
      console.log('驳回失败',res.data)
      ElMessage.error('驳回失败');
    }
  }catch(error){
    console.log('驳回失败',error);
    ElMessage.error('网络错误，失败')
  }
};

// 结算明细数据
const settlementItems = ref([
  {
    account: "",
    amount: 0,
    method: "",
    settlementNo: "",
    remark: "",
  },
]);

// 合计金额
const totalAmount = ref(0);
// 表格行样式
const tableCellStyle = ({ row }) => {
  if (row.isTotalRow) {
    return { "background-color": "#fff3cd", "font-weight": "bold" };
  }
  return {};
};

// 判断是否是新增行
const isTotalRow = (index) => {
  return index === settlementItems.value.length - 1;
};

// 判断是否是可删除行
const isDeleteRow = (index) => {
  return (
    index < settlementItems.value.length - 1 && settlementItems.value.length > 1
  );
};

// 第一个表格的操作函数
const addSettlementRow = (index) => {
  settlementItems.value.splice(index, 0, {
    account: "",
    amount: 0,
    method: "",
    settlementNo: "",
    remark: "",
  });
  calculateTotal();
};

const removeSettlementRow = (index) => {
  settlementItems.value.splice(index, 1);
  calculateTotal();
};

// 第二个表格的操作函数
const addSourceDocRow = () => {
  SourceDocuments.value.push({
    docNo: "",
    businessType: "",
    docDate: "",
    slipPrice: 0,
    writtenOffAmount: 0,
    currentWriteOffAmount: 0,
    remark: "",
  });
};

const removeSourceDocRow = (index) => {
  SourceDocuments.value.splice(index, 1);
};
// 判断源单表格是否是最后一行（用于显示“+”）
const isSourceDocLastRow = (index) => {
  return index === SourceDocuments.value.length - 1;
};

// 判断源单表格是否可删除（非最后一行且总数 > 1）
const canDeleteSourceDocRow = (index) => {
  return SourceDocuments.value.length > 1 && index < SourceDocuments.value.length - 1;
};

// 计算合计金额
const calculateTotal = () => {
  totalAmount.value = settlementItems.value
    .filter((item) => !item.isTotalRow)
    .reduce((sum, item) => sum + (Number(item.amount) || 0), 0);

  // 更新合计行
  if (settlementItems.value[settlementItems.value.length - 1].isTotalRow) {
    settlementItems.value[settlementItems.value.length - 1].amount =
      totalAmount.value;
  }
};

// 初始化表格数据
const initTableData = () => {
  // 添加合计行
  settlementItems.value.push({
    account: "合计:",
    amount: 0,
    method: "",
    settlementNo: "",
    remark: "",
    isTotalRow: true,
  });
};


const handleWriteOffInput = (row) => {
  const current = parseFloat(row.currentWriteOffAmount) || 0;
  
  // 普通采购：输入负数时立即修正为0.01
  if (row.isRefund === 0) {
    if (current < 0.01) {
      row.currentWriteOffAmount = 0.01;
      // 触发视图更新（解决v-model.number延迟问题）
      row.currentWriteOffAmount = Number(row.currentWriteOffAmount.toFixed(2));
    }
  } 
  // 采购退货：输入正数时立即修正为-0.01
  else if (row.isRefund === 1) {
    if (current >= 0) {
      row.currentWriteOffAmount = -0.01;
      row.currentWriteOffAmount = Number(row.currentWriteOffAmount.toFixed(2));
    }
  }
};
const preventInvalidInput = (event, row) => {
  const key = event.key;

  if (key === 'e' || key === 'E') {
    event.preventDefault();
    return;
  }

  // 必须确保 row.isRefund 存在
  if (row.isRefund === 0 && key === '-') {
    event.preventDefault();
    ElMessage.warning("普通采购的核销金额不能为负数");
    return;
  }

  // 允许负号仅在 isRefund === 1 时
  if (row.isRefund === 1 && key === '-' && event.target.selectionStart !== 0) {
    // 如果光标不在开头，也禁止输入负号（避免中间插入）
    event.preventDefault();
    return;
  }

  const validKeys = ['0','1','2','3','4','5','6','7','8','9','.', 'Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'];
  if (!validKeys.includes(key) && !event.ctrlKey && !event.metaKey) {
    event.preventDefault();
  }
};

//计算是否核算金额超过未核销金额
const validateWriteOffAmount = (row) => {
  let value = parseFloat(row.currentWriteOffAmount) || 0;

  if (row.isRefund === 0) {
    // 普通采购：必须 > 0
    if (value <= 0) {
      ElMessage.warning(`源单 ${row.docNo} 为普通采购，核销金额必须大于0`);
      value = 0.01;
    }
    const max = parseFloat(row.unwrittenOffAmount) || 0;
    if (value > max) {
      ElMessage.warning(`核销金额不能超过未核销金额 ${max.toFixed(2)}`);
      value = max;
    }
  } else if (row.isRefund === 1) {
    // 采购退货：必须 < 0
    if (value >= 0) {
      ElMessage.warning(`源单 ${row.docNo} 为采购退货，核销金额必须为负数`);
      value = -0.01;
    }
    const maxAbs = Math.abs(parseFloat(row.unwrittenOffAmount) || 0);
    if (Math.abs(value) > maxAbs) {
      ElMessage.warning(`核销金额绝对值不能超过 ${maxAbs.toFixed(2)}`);
      value = -maxAbs;
    }
  }

  row.currentWriteOffAmount = Number(value.toFixed(2));
  calculateTotal(); // 触发合计更新
};

// 表格合计计算方法
const getSummaries = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = "合计";
      return;
    }

    // 根据列的prop属性计算不同列的合计
    const field = column.property;
    if (
      [
        "docAmount",
        "writtenOffAmount",
        "unwrittenOffAmount",
        "currentWriteOffAmount",
      ].includes(field)
    ) {
      const values = data.map((item) => Number(item[field]) || 0);
      sums[index] = values.reduce((prev, curr) => prev + curr, 0).toFixed(2);
    } else {
      sums[index] = ""; // 非金额列不显示合计
    }
  });

  return sums;
};

//计算自动核销
const autoWriteOff = () => {
  if (SourceDocuments.value.length === 0) {
    ElMessage.warning("请先选择源单");
    return;
  }

  const totalPayment = totalAmount.value;
  if (totalPayment <= 0) {
    ElMessage.warning("付款金额必须大于0");
    return;
  }

  // 按单据日期升序排序
  const sortedDocs = [...SourceDocuments.value].sort(
    (a, b) => new Date(a.docDate) - new Date(b.docDate)
  );

  let remainingAmount = totalPayment;

  // 普通采购单（正数核销）
  const purchaseDocs = sortedDocs.filter(doc => doc.isRefund === 0);
  for (const doc of purchaseDocs) {
    if (remainingAmount <= 0) break;

    const maxCanWriteOff = Number(doc.unwrittenOffAmount) || 0;
    const actualWriteOff = Math.min(maxCanWriteOff, remainingAmount);
    
    // 普通采购：核销金额为正数，至少0.01
    doc.currentWriteOffAmount = Number(Math.max(0.01, actualWriteOff).toFixed(2));
    remainingAmount -= actualWriteOff;
  }

  // 采购退货单（负数核销）
  if (remainingAmount > 0.01) {
    const refundDocs = sortedDocs.filter(doc => doc.isRefund === 1);
    for (const doc of refundDocs) {
      if (remainingAmount <= 0) break;

      const maxCanWriteOffAbs = Math.abs(Number(doc.unwrittenOffAmount) || 0);
      const actualWriteOffAbs = Math.min(maxCanWriteOffAbs, remainingAmount);
      
      // 采购退货：核销金额为负数
      doc.currentWriteOffAmount = Number(-actualWriteOffAbs.toFixed(2));
      remainingAmount -= actualWriteOffAbs;
    }
  }

  calculateTotal();
};

//付款备注
const note = ref("");

// 计算总核销金额
const totalWriteOff = computed(() => {
  return SourceDocuments.value.reduce(
    (sum, doc) => sum + (Number(doc.currentWriteOffAmount) || 0),
    0
  );
});

// 计算预付款金额（总付款 - 总核销）
const remainAmount = computed(() => {
  const diff = Number(totalAmount.value) - Number(totalWriteOff.value);
  return diff > 0 ? Number(diff.toFixed(2)) : 0;
});
// 页面加载时初始化表格
initTableData();

//控制状态图片
const showStatus = ref(false);
const statusImageUrl = ref("");
const statusAltText = ref("");

const imagePaths = {
  waiting: require("@/assets/waitingpass.png"),
  passed: require("@/assets/passed.png"),
};

// 重置表单
const resetForm = () => {
  TotalDebt.value = "";
  selectedSupplier.value = {
    SupplierName: "",
    SupplierCode: "",
    id: null,
    code: null
  };
  form.supplier_name = "";
  form.supplier_code = "";

  responsible.value = "";
  date.value = dayjs().format('YYYY-MM-DD');
  note.value = "";

  // 重置结算明细
  settlementItems.value = [
    {
      account: "",
      amount: 0,
      method: "",
      settlementNo: "",
      remark: "",
    },
    {
      account: "合计:",
      amount: 0,
      method: "",
      settlementNo: "",
      remark: "",
      isTotalRow: true,
    }
  ];
  SourceDocuments.value = [];
  availableSourceDocs.value = [];
  generateDefaultBillNo();
  showStatus.value = false;
};

//新增
const addNew = () => {
  // 如果当前在编辑模式（URL 有 code），则跳转到无参路径，触发新增
  if (route.query.code) {
    router.push({ 
      path: '/finance/payment-slip',
      query: {} 
    });
  } else {
    resetForm();
  }
  resetForm();
};

</script>

<style scoped>
.bills {
  position: relative;
  background: #ffffff;
  border: 1px solid #cfcfcf;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  padding: 10px 20px 10px 20px;
  /* height: 100%; */
}
.label_input {
  margin-right: 10px;
}
.searchDiv {
  display: inline-block;
  margin-right: 15px;
}
.el-table .selected-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);
  background-color: var(--el-table-tr-bg-color);
}
.bill-no {
  cursor: pointer;
  padding: 0 5px;
  border-radius: 4px;
  transition: all 0.3s;
}

.bill-no:hover {
  background-color: #f5f5f5;
  text-decoration: underline;
}

.settlement-table {
  margin-top: 20px;
}

.el-table .cell {
  padding: 8px 12px;
}
.el-table__footer .el-table__cell {
  background-color: #fff3cd !important; /* 橙色背景 */
  font-weight: bold !important;
}

.note {
  margin-top: 7px;
}

/* 固定在右下角的样式 */
.status-indicator {
  position: absolute; /* 固定定位，不随滚动条移动 */
  right: 50px; /* 距离右边20px */
  bottom: 100px; /* 距离底部20px */
  z-index: 9999; /* 确保显示在最上层 */
  border-radius: 4px; /* 圆角边框 */
  overflow: hidden; /* 内容超出部分隐藏 */
}

/* 图片样式 */
.status-image {
  width: 120px; /* 根据实际图片大小调整 */
  height: 120px; /* 保持宽高比 */
  display: block;
}

/* 标记必填项 */
.el-table .el-table__header .cell .required {
  color: #f56c6c;
  margin-right: 2px;
}

.middle-div {
  float: right;
  margin-top: 5px;
  margin-bottom: 5px;
}

:deep(.el-table) .el-table__footer .el-table__cell {
  background-color: #fff3cd !important;
  font-weight: bold !important;
}
.note {
  margin-top: 7px;
}
:deep(.el-table .el-table__row.summary-row) {
  background-color: #f8f8f8 !important;
  font-weight: bold;
}

:deep(.el-table .el-table__row.summary-row:hover > td) {
  background-color: #fff4bf !important;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #fff4bf !important;
}
</style>